package loadbalance

import "errors"

func nextRoundRobinServer(pool *EndpointPool) (*Endpoint, error) {
	if pool.curWeights == nil {
		panic("no round-robin init status")
	}

	maxWeight := 0
	weightSum := 0
	var best *Endpoint
	bestIdx := 0

	for i := 0; i < len(pool.eps); i++ {
		ep := pool.eps[i]
		if !ep.CheckAvail() {
			continue
		}

		pool.curWeights[i] += ep.Weight
		weightSum += ep.Weight

		if maxWeight == 0 || pool.curWeights[i] > maxWeight {
			maxWeight = pool.curWeights[i]
			best = ep
			bestIdx = i
		}
	}

	if best == nil {
		return nil, errors.New("no avaliable endpoint in round_robin picker")
	}

	pool.curWeights[bestIdx] -= weightSum
	return best, nil
}
